package com.woniuxy.provider.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.common.result.Result;
import com.woniuxy.provider.model.entity.Stu;
import com.woniuxy.provider.service.StuService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import com.woniuxy.common.model.dto.PageRequest;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/stu")
@Slf4j
public class StuController {
    @Autowired
    private StuService stuService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping("/list")
    @ApiOperation("分页查询全部")
    public Result<Page<Stu>> list(@RequestBody PageRequest pageRequest) {
        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();

        Page<Stu> page = stuService.list(pageNum, pageSize);
        log.info("我是生产者，我生产了一页数据");
        return Result.ok(page);
    }

    @PostMapping("/remove")
    @ApiOperation("删除")
    public Result remove(@RequestParam("id") Integer id) {
        log.info("id = " + id + " 我是生产者，我生产了一条删除消息");
        try {
            // 1. 从数据库删除学生数据
            boolean isRemoved = stuService.removeById(id);
            if (!isRemoved) {
                return Result.fail("删除失败，学生不存在！");
            }
            // 发送删除消息到 RabbitMQ，分别用于 Redis 和 Elasticsearch
            rabbitTemplate.convertAndSend("student.exchange","student.delete.redis.routingkey", id);  // 发送到 Redis 删除队列
            rabbitTemplate.convertAndSend("student.exchange","student.delete.es.routingkey", id);    // 发送到 Elasticsearch 删除队列

            return Result.ok("删除成功，已发送删除消息至 RabbitMQ！");
        } catch (Exception e) {
            log.error("删除学生失败", e);
            return Result.fail("删除失败：" + e.getMessage());
        }
    }



}
